package com.jxb.currentLimiting;

/**
 * 漏桶限流算法
 */
public class LeakyBucket {

    public static long timeStamp = System.currentTimeMillis();//当前时间
    public static long capacity=100;//桶的容量
    public static long rate=1;//水流出的速度(系统处理请求的速度)
    public static long water=10;//当前水量(当前累计的请求数)

    public static void main(String[] args) {
        while (true) {
            if (!limit()) {
                System.out.println("已经限流.......");
                System.out.println("water--->"+water);
                break;
            }
        }
    }

    public static boolean limit() {
        long now = System.currentTimeMillis();
        //计算剩余水量
        water = Math.max(0,water-((now-timeStamp)/1000)*rate);
        timeStamp = now;
        if ((water + 1) <= capacity) {
            //尝试加水，水没有满
            water+=1;
            return true;
        }else {
            //水满，拒绝加水
            return false;
        }
    }

}
